<template>
    <!--    搜索条件-->
    <div class="contentContainer">
        <a-form
                ref="formRef"
                :model="searchData">
            <a-row :gutter="32">
                <a-col :span="8">
                    <a-form-item label="用户名称">
                        <a-input v-model:value="searchData.username"></a-input>
                    </a-form-item>
                </a-col>
                <a-col :span="8">
                    <a-form-item label="账号">
                        <a-input v-model:value="searchData.userCode"></a-input>
                    </a-form-item>
                </a-col>
                <a-col :span="8">
                    <a-form-item label="状态">
                        <a-select v-model:value="searchData.status" style="width: 200px">
                            <a-select-option :value="undefined">全部</a-select-option>
                            <a-select-option :value="0">有效</a-select-option>
                            <a-select-option :value="1">无效</a-select-option>
                        </a-select>
                    </a-form-item>
                </a-col>

            </a-row>
            <a-row :gutter="64">
                <a-col :span="10">
                    <a-form-item label="创建时间">
                        <a-range-picker v-model:value="startAndEndDate" show-time/>
                    </a-form-item>
                </a-col>
                <a-col :span="8">
                    <a-form-item>
                        <a-space>
                            <a-button type="primary" @click="load(1)">搜索</a-button>
                            <a-button type="default" @click="reset()">重置</a-button>
                        </a-space>
                    </a-form-item>
                </a-col>
            </a-row>
        </a-form>
    </div>
    <!--表格-->
    <div class="contentContainer">
        <a-row>
            <a-space style="float: right">
                <a-button type="primary" @click="openModal({})" style="margin-bottom: 10px">新增</a-button>
                <a-button type="primary" ghost style="margin-bottom: 10px" @click="importVisible = true">导入</a-button>
                <a-button type="primary" @click="exportUserInfo(true)" ghost style="margin-bottom: 10px">导出全部</a-button>
            </a-space>
        </a-row>
        <a-row :gutter="16">
            <a-col :span="6">
                <a-alert :message="'选中了《' + selectedUserRowKeys.length +'》条用户记录~~'" type="info" show-icon>
                    <template #icon>
                        <smile-outlined/>
                    </template>
                </a-alert>
            </a-col>
            <a-col>
                <a-dropdown>
                    <template #overlay>
                        <a-menu>
                            <a-menu-item key="1">
                                <a-button size="small" type="link"
                                          :disabled="selectedUserRowKeys.length == 0"
                                          @click="exportUserInfo(false)">导出
                                </a-button>
                            </a-menu-item>
                            <a-menu-item key="2">
                                <a-button size="small" type="link"
                                          @click="changeStatusByUserIds(0)"
                                          :disabled="selectedUserRowKeys.length == 0">有效
                                </a-button>
                            </a-menu-item>
                            <a-menu-divider></a-menu-divider>
                            <a-menu-item key="3">
                                <a-button size="small" type="link"
                                          :disabled="selectedUserRowKeys.length == 0"
                                          danger>删除
                                </a-button>
                            </a-menu-item>
                            <a-menu-item key="4">
                                <a-button size="small" type="link"
                                          @click="changeStatusByUserIds(1)"
                                          :disabled="selectedUserRowKeys.length == 0"
                                          danger>无效
                                </a-button>
                            </a-menu-item>
                        </a-menu>
                    </template>
                    <a-button size="large" type="primary" ghost>
                        操作
                        <DownOutlined/>
                    </a-button>
                </a-dropdown>
            </a-col>
        </a-row>

        <a-table bordered
                 style="margin-top: 10px"
                 size="small"
                 :row-selection="{
                    selectedRowKeys: selectedUserRowKeys,
                    onChange: onSelectUserChange,
                    preserveSelectedRowKeys: true,
                    hideDefaultSelections: true,
                    selections: [Table.SELECTION_ALL, Table.SELECTION_INVERT, Table.SELECTION_NONE]
                 }"
                 row-key="id"
                 :pagination="false"
                 :dataSource="dataSource"
                 :columns="columns">
            <template #bodyCell="{text,index,column,record}">
                <div v-if="column.key == 'sex'">
                    {{text == 1 ? '男' : '女'}}
                </div>
                <div v-if="column.key == 'status'">
                    {{text == 0 ? '有效' : '无效'}}
                </div>
                <div v-if="column.key == 'action'">
                    <a-space>
                        <a-button type="primary" ghost @click="openModal(record)">编辑</a-button>
                        <a-popconfirm
                                title="删除数据后无法再次查看！是否确认删除?"
                                ok-text="是"
                                cancel-text="否"
                                @confirm="okDelete(record.id)"
                        >
                            <a-button ghost type="danger">删除</a-button>
                        </a-popconfirm>
                        <a-dropdown placement="topLeft">
                            <a @click.prevent>
                                更多
                                <DownOutlined/>
                            </a>
                            <template #overlay>
                                <a-menu>
                                    <a-menu-item key="0">
                                        <a-button size="small" type="link" ghost
                                                  @click="openAssociateDrawer(record.id)">关联角色
                                        </a-button>
                                    </a-menu-item>
                                    <a-menu-item key="1">
                                        <a-button size="small" type="link" ghost @click="openUserInfoDrawer">详情
                                        </a-button>
                                    </a-menu-item>
                                    <a-menu-divider/>
                                    <a-menu-item key="3">
                                        <a-popconfirm
                                                title="是否确认让该用户状态重新变为有效?"
                                                ok-text="是"
                                                cancel-text="否"
                                                @confirm="changeStatus(record,0)"
                                                v-if="record.status == 1"
                                        >
                                            <a-button size="small" type="link">有效</a-button>
                                        </a-popconfirm>
                                        <a-popconfirm
                                                title="是否确认让该用户状态变为无效?"
                                                ok-text="是"
                                                cancel-text="否"
                                                @confirm="changeStatus(record,1)"
                                                v-if="record.status == 0"
                                        >
                                            <a-button size="small" type="link" danger>无效</a-button>
                                        </a-popconfirm>
                                    </a-menu-item>
                                </a-menu>
                            </template>
                        </a-dropdown>
                    </a-space>
                </div>
            </template>
        </a-table>
        <a-pagination style="margin-top: 10px; text-align: right"
                      v-model:current="pagination.current"
                      v-model:pageSize="pagination.pageSize"
                      show-quick-jumper
                      show-size-changer
                      :total="pagination.total"
                      :show-total="total => `总 ${total} 条数据`"
                      :page-size-options="pageSizeOptions"
                      @change="onPageChange"/>
    </div>
    <!--编辑模态框-->
    <a-modal v-model:visible="visible" :title="modalTitle" @ok="handleOk">
        <a-form
                ref="formRef"
                :label-col="{ span: 6 }"
                :wrapper-col="{ span: 18 }"
                :model="user">
            <a-form-item label="账号">
                <a-input v-model:value="user.userCode"></a-input>
            </a-form-item>
            <a-form-item label="用户名">
                <a-input v-model:value="user.username"></a-input>
            </a-form-item>
            <a-form-item label="性别">
                <a-radio-group v-model:value="user.sex">
                    <a-radio :value="1">男</a-radio>
                    <a-radio :value="0">女</a-radio>
                </a-radio-group>
            </a-form-item>
            <a-form-item label="电话">
                <a-input v-model:value="user.phone"></a-input>
            </a-form-item>
            <a-form-item label="邮箱">
                <a-input v-model:value="user.email"></a-input>
            </a-form-item>
            <a-form-item label="生日">
                <a-date-picker v-model:value="user.birthday"/>
            </a-form-item>
            <a-form-item label="状态">
                <a-switch v-model:checked="user.status"
                          :checked-value="0"
                          :un-checked-value="1"
                          checked-children="有效"
                          un-checked-children="无效"/>
            </a-form-item>
            <a-form-item label="备注">
                <a-input v-model:value="user.remark"></a-input>
            </a-form-item>
        </a-form>
    </a-modal>
    <!--导入文件模态框-->
    <a-modal v-model:visible="importVisible" title="导入用户数据">
        <a-upload-dragger
                v-model:fileList="fileList"
                name="file"
                :multiple="false"
                :before-upload="onBeforeUpload"
        >
            <p class="ant-upload-drag-icon">
                <inbox-outlined></inbox-outlined>
            </p>
            <p class="ant-upload-text">点击或拖拽文件到此处上传</p>
            <p class="ant-upload-hint">
                请上传符合用户导入信息的Excel文件
            </p>
        </a-upload-dragger>
        <template #footer>
            <a-space>
                <a-button type="default" @click="onCloseUploadModal">取消</a-button>
                <a-button type="primary"
                          @click="onUpload"
                          :loading="uploading"
                          :disabled="fileList.length == 0">
                    上传
                </a-button>
            </a-space>
        </template>
    </a-modal>
    <!--    关联角色抽屉-->
    <a-drawer
            v-model:visible="associateDrawerVisible"
            title="关联角色"
            placement="right"
            width="600"
            @close="associateDrawerVisible = false"
    >
        <a-input-search
                v-model:value="keyword1"
                style="margin-top: 10px"
                placeholder="请输入关键词搜索..."
                enter-button
                @search="onSearchAssociateRole"
        />
        <a-space>
            <a-button type="primary" style="margin-top: 10px" @click="openChildrenDrawer">关联角色</a-button>
            <a-popconfirm
                    title="是否确认解除关联?"
                    ok-text="是"
                    cancel-text="否"
                    :disabled="selectedRowKeys1.length === 0"
                    @confirm="cancelAssociateRoleHandler"
            >
                <a-button type="danger" :disabled="selectedRowKeys1.length === 0" style="margin-top: 10px">取消关联
                </a-button>
            </a-popconfirm>
        </a-space>
        <a-table :dataSource="associateRoleList"
                 style="margin-top: 10px"
                 :columns="roleColumns"
                 :pagination="false"
                 :row-selection="{ selectedRowKeys: selectedRowKeys1, onChange: onSelectChange1 }"
                 row-key="id"
                 size="small"
                 bordered>
        </a-table>
        <a-drawer
                v-model:visible="childrenDrawerVisible"
                title="用户未关联角色"
                placement="right"
                width="600"
                @close="childrenDrawerVisible = false"
        >
            <a-input-search
                    v-model:value="keyword2"
                    style="margin-top: 10px"
                    placeholder="请输入关键词搜索..."
                    enter-button
                    @search="onSearchNotAssociateRole"
            />
            <a-table :dataSource="notAssociateRoleList"
                     style="margin-top: 10px"
                     :columns="roleColumns"
                     :row-selection="{ selectedRowKeys: selectedRowKeys2, onChange: onSelectChange2 }"
                     row-key="id"
                     :pagination="false"
                     size="small"
                     bordered>
            </a-table>
            <template #footer>
                <a-space style="float: right">
                    <a-button type="default" @click="childrenDrawerVisible = false">关闭</a-button>
                    <a-popconfirm
                            title="是否确认建立关联关系?"
                            ok-text="是"
                            cancel-text="否"
                            :disabled="selectedRowKeys2.length === 0"
                            @confirm="associateRoleHandler"
                    >
                        <a-button type="primary"
                                  :disabled="selectedRowKeys2.length === 0">
                            确认关联
                        </a-button>
                    </a-popconfirm>
                </a-space>
            </template>
        </a-drawer>
    </a-drawer>
    <!--    用户详情抽屉-->
    <a-drawer
            v-model:visible="userInfoDrawerVisible"
            title="用户详情"
            placement="right"
            @close="userInfoDrawerVisible = false"
    >

    </a-drawer>

</template>

<script setup>
    import {ref, onMounted} from 'vue'
    import axios from 'axios'
    import {message, Table} from 'ant-design-vue'
    import dayjs from "dayjs";
    import fileDownload from 'js-file-download'
    import {SmileOutlined, DownOutlined, InboxOutlined} from '@ant-design/icons-vue'

    const searchData = ref({})
    const columns = [
        {
            title: 'id',
            dataIndex: 'id',
            key: 'id',
        },
        {
            title: '账号',
            dataIndex: 'userCode',
            key: 'userCode',
        },
        {
            title: '姓名',
            dataIndex: 'username',
            key: 'username',
        },
        {
            title: '性别',
            dataIndex: 'sex',
            key: 'sex',
        },
        {
            title: '电话',
            dataIndex: 'phone',
            key: 'phone',
        },
        {
            title: '邮件',
            dataIndex: 'email',
            key: 'email',
        },
        {
            title: '生日',
            dataIndex: 'birthday',
            key: 'birthday',
        },
        {
            title: '状态',
            dataIndex: 'status',
            key: 'status',
        },
        {
            title: '备注',
            dataIndex: 'remark',
            key: 'remark',
        },
        {
            title: '操作',
            key: 'action',
            align: 'center'
        }
    ]
    const roleColumns = [
        {
            title: '角色名称',
            dataIndex: 'name',
            key: 'name',
            width: '30%'
        },
        {
            title: '备注',
            dataIndex: 'remark',
            key: 'remark',
        }
    ]
    const dataSource = ref([])
    const associateRoleList = ref([])
    const notAssociateRoleList = ref([])
    const user = ref({})
    const userId = ref()
    const modalTitle = ref('')
    const selectedRowKeys1 = ref([])
    const selectedRowKeys2 = ref([])
    const selectedUserRowKeys = ref([])

    const pagination = ref({
        current: 1,
        pageSize: 5,
    })
    const pageSizeOptions = ref(['5', '10', '20', '30', '50', '100'])
    const startAndEndDate = ref([])
    const keyword1 = ref('')
    const keyword2 = ref('')

    const visible = ref(false)
    const userInfoDrawerVisible = ref(false)
    const associateDrawerVisible = ref(false)
    const childrenDrawerVisible = ref(false)
    const importVisible = ref(false)
    const uploading = ref(false)

    const fileList = ref([])
    const formData = new FormData();

    const onBeforeUpload = (file) => {
        console.log("需要上传的文件", file)

        fileList.value = []
        fileList.value.push(file)
        formData.delete('file')
        formData.append('file', file)

        return false
    }

    const onCloseUploadModal = () => {
        fileList.value = []
        importVisible.value = false
    }

    const onUpload = () => {
        console.log("文件列表", fileList.value)
        // console.log("文件列表的第一个", Object.prototype.toString.call(fileList.value[0]))
        // const formData = new FormData();

        formData.append('file', fileList.value[0])

        console.log("formData文件：", formData.get('file'))
        uploading.value = true;

        axios.post('user/importExcel', formData, {
            headers: {
                'Content-type': 'multipart/form-data',
            }
        }).then(rs => {
            if (rs.data.code === 200) {
                message.success('导入用户信息成功')
                fileList.value = []
                uploading.value = false
            } else {
                message.error(rs.data.message)
                uploading.value = false
            }
        }).catch(() => {
            uploading.value = false
        })
    }

    const exportUserInfo = (flag) => {
        axios.get('user/exportExcel', {
            params: {
                ids: flag ? null : selectedUserRowKeys.value + ''
            },
            responseType: 'blob'
        }).then(rs => {
            fileDownload(rs.data, '用户数据.xlsx')
        })
    }

    const openModal = (obj) => {
        user.value = JSON.parse(JSON.stringify(obj))
        if (obj.id) {
            modalTitle.value = '修改'
            user.value.birthday = dayjs(user.value.birthday)
        } else {
            modalTitle.value = '新增'
            user.value.status = 0
            user.value.password = '123'
        }
        console.log("模态框的用户数据", user.value)
        visible.value = true
    }

    const openUserInfoDrawer = () => {
        userInfoDrawerVisible.value = true
    }

    const openAssociateDrawer = (id) => {
        userId.value = id
        keyword1.value = ''
        onSearchAssociateRole()
        associateDrawerVisible.value = true
    }

    const openChildrenDrawer = () => {
        keyword2.value = ''
        onSearchNotAssociateRole()
        childrenDrawerVisible.value = true
    }

    const onSearchAssociateRole = () => {
        selectedRowKeys1.value = []
        axios.get('role/queryByUserIdAndKeyword', {
            params: {
                userId: userId.value,
                keyword: keyword1.value
            }
        }).then(rs => {
            if (rs.data.code == 200) {
                associateRoleList.value = rs.data.data
            } else {
                message.error(rs.data.message)
            }
        })
    }

    const onSearchNotAssociateRole = () => {
        selectedRowKeys2.value = []
        axios.get('role/queryNotAssociateRoleByUserIdAndKeyword', {
            params: {
                userId: userId.value,
                keyword: keyword2.value
            }
        }).then(rs => {
            if (rs.data.code == 200) {
                notAssociateRoleList.value = rs.data.data
            } else {
                message.error(rs.data.message)
            }
        })
    }

    const onSelectChange1 = (keys) => {
        console.log("选中的非关联角色id：", keys)
        selectedRowKeys1.value = keys
    }

    const onSelectChange2 = (keys) => {
        console.log("选中的非关联角色id：", keys)
        selectedRowKeys2.value = keys
    }
    const onSelectUserChange = (keys) => {
        console.log("选中的用户：", keys)
        selectedUserRowKeys.value = keys
    }


    const associateRoleHandler = () => {
        axios.post('user-role/associateRolesByUserId', {
            userId: userId.value,
            roleIds: selectedRowKeys2.value
        }).then(rs => {
            if (rs.data.code == 200) {
                message.success('关联角色成功')
                childrenDrawerVisible.value = false
                onSearchAssociateRole()
            } else {
                message.error(rs.data.message)
            }
        })
    }

    const cancelAssociateRoleHandler = () => {
        axios.post('user-role/cancelAssociateRolesByUserId', {
            userId: userId.value,
            roleIds: selectedRowKeys1.value
        }).then(rs => {
            if (rs.data.code == 200) {
                message.success('角色解除关联成功')
                onSearchAssociateRole()
            } else {
                message.error(rs.data.message)
            }
        })
    }


    const handleOk = () => {
        console.log("提交的用户数据", user.value)
        axios.post('user/saveOrUpdate', user.value).then(rs => {
            if (rs.data.code == 200) {
                if (user.value.id) {
                    message.success("用户《" + user.value.username + "》的数据修改成功")
                } else {
                    message.success("成功添加新用户《" + user.value.username + "》")
                }
                visible.value = false
                load()
            } else {
                message.error(rs.data.message)
            }
        })
    }

    const okDelete = (id) => {
        console.log("要删除的用户的id", id)
        axios.delete('user/deleteById/' + id).then(rs => {
            if (rs.data.code == 200) {
                message.success("删除成功")
                load(1)
            } else {
                message.error(rs.data.message)
            }
        })
    }

    const changeStatus = (obj, status) => {
        user.value = JSON.parse(JSON.stringify(obj))
        user.value.status = status
        user.value.birthday = dayjs(user.value.birthday)
        handleOk()
    }

    const changeStatusByUserIds = (status) => {
        axios.post('', {
            status: status,
            userIds: selectedUserRowKeys.value
        }).then(rs => {
            if (rs.data.code === 200) {
                message.success('批量操作成功')
            } else {
                message.error(rs.data.message)
            }
        })
    }

    const load = (pageNum) => {
        if (pageNum == 1) {
            pagination.value.current = 1
        }
        console.log("查询的参数", searchData.value)
        console.log("查询的参数1", startAndEndDate.value)
        console.log("查询的参数2", startAndEndDate.value.length == 0)
        axios.get('user/queryPage', {
            params: {
                username: searchData.value.username,
                userCode: searchData.value.userCode,
                status: searchData.value.status,
                startDate: startAndEndDate.value.length == 0 ? null : dayjs(startAndEndDate.value[0]).valueOf(),
                endDate: startAndEndDate.value.length == 0 ? null : dayjs(startAndEndDate.value[1]).valueOf(),
                pageNum: pagination.value.current,
                pageSize: pagination.value.pageSize,
            }
        }).then(rs => {
            console.log("用户查询结果rs", rs)
            console.log("用户查询结果", rs.data)
            if (rs.data.code == 200) {
                dataSource.value = rs.data.data.records
                pagination.value.total = rs.data.data.total
            }
        })
    }

    const reset = () => {
        searchData.value = {}
        startAndEndDate.value = []
        load(1)
    }

    const onPageChange = (pageNum, pageSize) => {
        pagination.value.current = pageNum
        pagination.value.pageSize = pageSize
        load()
    }

    onMounted(() => {
        load()
    })
</script>

<style>
    .contentContainer {
        background: #fff;
        margin: 10px 10px 0 10px;
        padding: 15px;
    }
</style>